﻿#define _CRT_SECURE_NO_WARNING
#include"SList.h"


//打印节点函数
void Printf(SLTNode* phead)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		printf("%d ->", pcur->data);
		pcur = pcur->next;
	}
	printf("NULL\n");
}

//申请节点函数
SLTNode* ByNode(SLDataType x)
{
	SLTNode* NewNode = (SLTNode*)malloc(sizeof(SLTNode));
	if (NewNode == NULL)
	{
		perror("malloc");
		exit(1);
	}
	NewNode->data = x;
	NewNode->next = NULL;
	return NewNode;
}
//1. 头插
void SLTPushFront(SLTNode** pphead, SLDataType x)
{
	assert(pphead);
	//申请节点
	SLTNode* newnodde = ByNode(x);
	//更改指针指向
	newnodde->next = *pphead;
	*pphead = newnodde;
}
//2. 尾插
void SLTPushBack(SLTNode** pphead, SLDataType x)
{
	assert(pphead);
	//申请节点
	SLTNode* newnode = ByNode(x);
	//分情况讨论
	if (*pphead == NULL)
	{
		*pphead = newnode;
	}
	else
	{
		//遍历到最后一个节点处插入
		SLTNode* pcur = *pphead;
		while (pcur->next)
		{
			pcur = pcur->next;
		}
		//找到了，尾插
		pcur->next = newnode;
	}
}
//3. 尾删
void SLTPopBack(SLTNode** pphead)
{
	assert(pphead && *pphead);

	//要考虑链表两种情况
	if ((*pphead)->next==NULL)
	{
		free(*pphead);
		*pphead = NULL;
	}
	else
	{
		//遍历到最后一个
		SLTNode* pcur = *pphead;
		SLTNode* priv = NULL;
		while (pcur->next)
		{
			priv = pcur;
			pcur = pcur->next;
		}
		priv->next = NULL;
		free(pcur);
		pcur = NULL;
	}
}
//4. 头删
void SLTPopFront(SLTNode** pphead)
{
	assert(pphead && *pphead);
	SLTNode* next = (*pphead)->next;
	free(*pphead);
	*pphead = next;

}
//5. 查找
SLTNode* SLTFind(SLTNode* phead, SLDataType x)
{
	SLTNode* pcur = phead;
	while (pcur)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}
//6. 在指定位置之前插⼊数据
void SLTInsert(SLTNode** pphead, SLTNode* pos, SLDataType x)
{
	assert(pphead && pos);
	SLTNode* newnode = ByNode(x);
	//分情况
	if ((*pphead)== pos)
	{
		//头插
		SLTPushFront(pphead,x);
	}
	else
	{
		//找到pos和前一个节点更改指向
		SLTNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = newnode;
		newnode->next = pos;
	}
}
//7. 在指定位置之后插⼊数据
void  SLTInsertAfter(SLTNode* pos, SLDataType x)
{
	assert(pos);
	SLTNode* newnode = ByNode(x);
	newnode->next = pos->next;
	pos->next = newnode;
}
//8. 删除pos节点
void SLTErase(SLTNode** pphead, SLTNode* pos)
{
	assert(pphead && pos);
	//分情况讨论
	if (*pphead == pos)
	{
		SLTPopFront(pphead);
	}
	else
	{
		//找到pos
		SLTNode* pcur = *pphead;
		while (pcur->next != pos)
		{
			pcur = pcur->next;
		}
		pcur->next = pos->next;
		free(pos);
		pos = NULL;
	}
}
//9. 删除pos之后的结点
void SLTEraseAfter(SLTNode* pos)
{
	assert(pos && pos->next);
	SLTNode* pnext = pos->next;
	pos->next = pnext->next;
	free(pnext);
	pnext = NULL;
}
//10. 销毁链表
void SListDestroy(SLTNode** pphead)
{
	assert(pphead);
	SLTNode* pcur = *pphead;
	while (pcur)
	{
		SLTNode* new = pcur->next;
		free(pcur);
		pcur = new;
	}
	*pphead = NULL;
}